package com.lagou.jdbc04;

import com.lagou.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * CREATE TABLE account(
 * id int primary key AUTO_INCREMENT,
 * name VARCHAR(10),
 * money DOUBLE
 * );
 * INSERT INTO account (NAME,money) VALUES ('tom',1000),('jack',1000);
 */
public class TestJDBCTransaction {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement("update account set money = money - ? where name = ?");
            preparedStatement.setDouble(1, 500.0);
            preparedStatement.setString(2, "tom");
            preparedStatement.executeUpdate();
            System.out.println(1 / 0);
            preparedStatement = connection.prepareStatement("update account set money = money + ? where name = ?");
            preparedStatement.setDouble(1, 500.0);
            preparedStatement.setString(2, "jack");
            preparedStatement.executeUpdate();
            connection.commit();
            System.out.println("转账成功！");
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                e.printStackTrace();
            }
        } finally {
            JDBCUtils.close(connection, preparedStatement);
        }
    }
}
